import {login, logout, getInfo, refreshToken, loginPhone} from '@/api/login'
import {getToken, setToken, setExpiresIn, removeToken} from '@/utils/auth.js'
// import profile from '@/assets/images/profile.jpg'
import {handleTree} from "@/utils/common";


// 定义的state初始值
const state = {
  token: getToken(),
  name: '',
  userId: '',
  avatar: '',
  deptId: '',
  deptName: '',
  roles: [],
  permissions: [],
  services: [],
  allServices: []
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_EXPIRES_IN: (state, time) => {
    state.expires_in = time
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER_ID: (state, id) => {
    state.userId = id
  },
  SET_DEPT_ID: (state, name) => {
    state.deptId = name
  },
  SET_DEPT_NAME: (state, name) => {
    state.deptName = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_SERVICES: (state, services) => {
    state.services = services
  },
  SET_ALLSERVICES: (state, allServices) => {
    state.allServices = allServices
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
};

const getters = {
  // token: (state) => state.token,
  // roles: (state) => state.userInfo?.roles,
  // realname: (state) => state.userInfo?.realname,
  // project_name: (state) => state.userInfo?.project_name,
};

const actions = {
  // 登录
  Login({commit}, userInfo) {
    const username = userInfo.username.trim()
    const {password, code,imageCode, uuid, loginType, phoneNumber} = userInfo
    return new Promise<void>((resolve, reject) => {
      // const {data} = {"data":{"access_token":"eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJuaWNrbmFtZSI6Iui2hee6p-euoeeQhuWRmCIsInVzZXJfa2V5IjoiMzQzOWFkNjktYTgyMC00ZTFhLTg2MTUtMTdlZTc0OTU4ZmE0IiwidXNlcm5hbWUiOiJhZG1pbiJ9.OT9Y8DojSbeD1yA5PiZu_v7Q0-DeqfSFu0aYtxfaIyvlL3sg4SqilAUOeOzsCPLl3hx8CSBaFXlVPB-2XzfMvQ","expires_in":720}}
      // setToken(data.access_token)
      // commit('SET_TOKEN', data.access_token)
      // setExpiresIn(data.expires_in)
      // commit('SET_EXPIRES_IN', data.expires_in)
      // resolve()
      if (loginType === 'phone') {
        loginPhone(phoneNumber, code).then(res => {
          const {data} = res
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve()
        }).catch(error => {
          reject(error)
        })
      } else {
        login(username.trim(), password, imageCode, uuid).then(res => {
          const {data} = res
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve()
        }).catch(error => {
          reject(error)
        })
      }


    })
  },
  // 获取用户信息
  GetInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const {user, allServices, services, roles, permissions} = <any>res;
        // const avatar = (user.avatar === "" || user.avatar == null) ? profile : user.avatar;
        if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
          commit('SET_ROLES', roles)
          commit('SET_PERMISSIONS', permissions)
        } else {
          commit('SET_ROLES', ['ROLE_DEFAULT'])
        }
        commit('SET_NAME', user.nickName)
        commit('SET_USER_ID', user.id)
        commit('SET_DEPT_ID', user.dept.id)
        commit('SET_DEPT_NAME', user.dept.deptName)
        commit('SET_AVATAR', user.avatar)
        commit('SET_SERVICES', services.map(service => ({
          ...service,
          sysMenus: handleTree(service.sysMenus, "id", "parentId", "children")
        })))
        commit('SET_ALLSERVICES', allServices)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 刷新token
  RefreshToken({commit, state}) {
    return new Promise<void>((resolve, reject) => {
      refreshToken().then(res => {
        setExpiresIn(res.data)
        commit('SET_EXPIRES_IN', res.data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出系统
  LogOut({commit, state}) {
    return new Promise<void>((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 前端 登出
  FedLogOut({commit}) {
    return new Promise<void>(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
